import { Button, Space } from "antd"
import dayjs from "dayjs"
import { useEffect } from "react"
import { useSelector } from "react-redux"

import { useLocale } from "@/locales"
import { AppState } from "@/stores"
import { rangeCurrentMonth, rangeLastNMonth, rangePastNDays, rangeToday, rangeYesterday, TimeRange } from "@/utils/times"

import { ShortcutOptionsType, TimeSelectionShortcutsProps } from "./types"

const TimeSelectionShortcuts = ({ options, onChange, value }: TimeSelectionShortcutsProps) => {
	const { formatMessage } = useLocale()
	const { currentAccountPeriod } = useSelector((state: AppState) => state.config)
	const currentAccountPeriodRange = currentAccountPeriod
		? ({
				label: formatMessage({ id: "common.utils.current" }),
				value: [dayjs(currentAccountPeriod.start), dayjs(currentAccountPeriod.end)]
		  } as ShortcutOptionsType)
		: {
				label: formatMessage({ id: "common.utils.current" }),
				value: null
		  }
	const shortcuts: (ShortcutOptionsType | { label: string; value?: null })[] = [
		currentAccountPeriodRange,
		{
			label: formatMessage({ id: "common.utils.today" }),
			value: rangeToday()
		},
		{
			label: formatMessage({ id: "common.utils.yesterday" }),
			value: rangeYesterday()
		},
		{
			label: formatMessage({ id: "common.utils.last_n_days" }, { n: 7 }),
			value: rangePastNDays(7)
		},
		{
			label: formatMessage({ id: "common.utils.last_n_days" }, { n: 14 }),
			value: rangePastNDays(14)
		},
		{
			label: formatMessage({ id: "common.utils.last_n_days" }, { n: 30 }),
			value: rangePastNDays(30)
		},
		{
			label: formatMessage({ id: "common.utils.last_month" }),
			value: rangeLastNMonth(1)
		},
		{
			label: formatMessage({ id: "common.utils.this_month" }),
			value: rangeCurrentMonth()
		}
	]

	const handleChange = (e: TimeRange) => {
		onChange?.(e)
	}
	useEffect(() => {
		console.log(dayjs(shortcuts[1].value?.[0]).unix(), dayjs(value?.[0]).unix())
	}, [value])
	// const stringToTimeRange = (s: string): TimeRange => {
	// 	const [s1, s2] = s.split("-")
	// 	return [dayjs(s1), dayjs(s2)]
	// }

	return (
		<Space.Compact>
			{(Array.isArray(options) ? options : shortcuts).map((option: { label: string; value?: TimeRange | null }) => {
				return (
					<Button
						disabled={!option.value}
						onClick={() => (option.value ? handleChange(option.value) : undefined)}
						key={option.label}
						type={
							value &&
							option.value &&
							dayjs(option.value[0]).unix() === dayjs(value[0]).unix() &&
							dayjs(option.value[1]).unix() === dayjs(value[1]).unix()
								? "primary"
								: undefined
						}
					>
						{option.label}
					</Button>
				)
			})}
		</Space.Compact>
	)
}

export default TimeSelectionShortcuts
